package com.hnxxxy.common.WebSocket;

import com.hnxxxy.common.annotation.LogAnno;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @EnableWebSocketMessageBroker ，使用此注解来标识使能WebSocket的broker.即使用broker来处理消息.
 */
//@Configuration用于定义配置类
@Configuration
@EnableWebSocketMessageBroker
@Slf4j
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    @LogAnno(description = "websocket连接")
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        log.info("-->请求方法：websocket连接");
        /*
         * 路径"/websocket-demo"被注册为STOMP端点，对外暴露，客户端通过该路径接入WebSocket服务
         */
        stompEndpointRegistry.addEndpoint("/websocket-demo").withSockJS();
    }

    @Override
    @LogAnno(description = "websocket信息")
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        /**
         * 用户可以订阅来自"/topic"的消息，
         * 在Controller中，可通过@SendTo注解指明发送目标，这样服务器就可以将消息发送到订阅相关消息的客户端
         *
         * 在本Demo中，使用topic来达到聊天室效果
         *
         * 客户端只可以订阅这个前缀的主题
         */
        registry.enableSimpleBroker("/topic");
        /*
         * 客户端发送过来的消息，需要以"/app"为前缀，再经过Broker转发给相应的Controller
         */
        registry.setApplicationDestinationPrefixes("/app");
    }
}
